class Order < ActiveRecord::Base
   
  has_many :order_items, :dependent => :destroy
  has_many :positions, :through => :order_items
  has_many :inside_positions, :through => :order_items
  
  validates_presence_of :plate_number,:message => "プレートナンバを入力してください"
  validates_presence_of :identity_number,:message => "識別番号を入力してください"
  validates_presence_of :placename,:message => "地名を選択してください"
  validates_presence_of :identity_letter,:message => "標識文字を選択してください"
  validates_presence_of :car_type,:message => "車種を選択してください"
  validates_presence_of :car_size,:message => "サイズ を選択してください"
  validates_presence_of :paint_type,:message => "塗装種類を選択してください "
  validates_numericality_of :identity_number,:message => "識別番号に数字を入力してください"
  validates_numericality_of :plate_number,:message => "プレートナンバに数字を入力してください"
  
  
  
  COLORS = [[220,220,220],[255,228,181],[240,248,255],[119,136,153],[100,149,237],[0,0,255],[0,100,0],[0,255,0],[165,42,42],[148,0,211],[187,255,255],
  [139,129,76],[255,52,179],[0,139,139],[255,130,171],[139,0,139],[144,238,144],[238,58,140],[190,190,190],[210,180,140]]
  
  TIME_UNIT = 60
  
  ROUTE = "E:/Program Files/scheme/projects/autoRepair/updates"
  #validates_presence_of :placename, :identity_letter, :identity_number, :car_type, :car_size, :paint_type, :plate_number
  #下面5个类方法用来生成5个csv文件
  def self.get_orders_file
  
    FasterCSV.open("#{Order::ROUTE}/Orders.csv", "w") do |csv|
      i = 0
      Order.find(:all).each do |record|
        if record.order_items.count > 0
          csv << [record.convert(record.recipe_name),nil,record.convert(record.recipe_name),0,nil,record.convert('F'),record.convert(" " + record.created_at.strftime("%Y/%m/%d %H:%M")),record.convert('F'),nil,nil,i]   
          i += 1
        end
      end 
    end
    
  end
  
  def self.get_recipes_file
    FasterCSV.open("#{Order::ROUTE}/Recipes.csv", "w") do |csv|
      Order.find(:all).each do |record| 
        if record.order_items.count > 0
          csv << [record.convert(record.recipe_name)]  
        end
      end 
    end
  end
  
  def self.get_parts_file
    FasterCSV.open("#{Order::ROUTE}/Parts.csv", "w") do |csv|
      Order.find(:all).each do |record|    
        record.part_file_of_order(csv)
      end 
    end
  end
  
  def self.get_partTasks_file
    r = COLORS[0][0]
    g = COLORS[0][1]
    b = COLORS[0][2]
    i = 1
    FasterCSV.open("#{Order::ROUTE}/PartTasks.csv", "w") do |csv|
      Order.find(:all).each do |record|    
        record.partTask_file_of_order(csv,r,g,b)
        r = COLORS[i][0]
        g = COLORS[i][1]
        b = COLORS[i][2]
        i += 1
      end 
    end
  end
  
  def self.get_partRelations_file
    FasterCSV.open("#{Order::ROUTE}/PartRelations.csv", "w") do |csv|
      Order.find(:all).each do |record|    
        record.partRelation_file_of_order(csv)
      end 
    end
  end
  
  #下面3个方法都是先把order对象中的指数的总值（order对象里的order_items集合中对象的各指数之和为order对象中对应各指数的总值）计算出来，只有总值不为零的才作为一行加入文件
  def partRelation_file_of_order(csv)
    count_sum_index
    i = 0
    i = judge_for_partRelation_file(@sum_uninstall_index,i,csv)
    i = judge_for_partRelation_file(@sum_metal_index,i,csv)
    i = judge_for_partRelation_file(@sum_cut_index,i,csv)
    #8.20 start
    i = judge_for_partRelation_file(@sum_frame_amend_set_index,i,csv)
    #end
    i = judge_for_partRelation_file(@sum_frame_amend_index,i,csv)
    i = judge_for_partRelation_file(@sum_metal_putty_index,i,csv)
    i = judge_for_partRelation_file(@sum_putty_index,i,csv)
    i = judge_for_partRelation_file(@sum_surface_index,i,csv)
    i = judge_for_partRelation_file(@sum_paint_index,i,csv)
    i = judge_for_partRelation_file(@sum_assemble_recombine,i,csv)
    i = judge_for_partRelation_file(@sum_polish,i,csv)
    if self.order_items.count > 0
      csv << [convert(recipe_name),i + 1,convert('S'),i,convert('E'),0] 
    end
  end
  
  def partTask_file_of_order(csv,r,g,b)
    count_sum_index
    i = 0
    i = judge_for_partTask_file(@sum_uninstall_index,"着工分解",i,r,g,b,csv)
    i = judge_for_partTask_file(@sum_metal_index,"凹修正鈑金",i,r,g,b,csv)
    i = judge_for_partTask_file(@sum_cut_index,"カット交換鈑金",i,r,g,b,csv)
    #8.20 start
    i = judge_for_partTask_file(@sum_frame_amend_set_index,"修正機セット",i,r,g,b,csv)
    #end
    i = judge_for_partTask_file(@sum_frame_amend_index,"フレーム修正",i,r,g,b,csv)
    i = judge_for_partTask_file(@sum_metal_putty_index,"鈑金パテ",i,r,g,b,csv)
    i = judge_for_partTask_file(@sum_putty_index,"塗装パテ",i,r,g,b,csv)
    i = judge_for_partTask_file(@sum_surface_index,"サフ足付け",i,r,g,b,csv)
    i = judge_for_partTask_file(@sum_paint_index,"塗装",i,r,g,b,csv)
    i = judge_for_partTask_file(@sum_assemble_recombine,"組付け組換え",i,r,g,b,csv)
    i = judge_for_partTask_file(@sum_polish,"磨き",i,r,g,b,csv)
    if self.order_items.count > 0
      csv << [convert(recipe_name),i,convert('T'),convert(recipe_name),r,g,b,100,convert("納車準備")] 
      csv << [convert(recipe_name),i,convert('F'),convert(recipe_name),r,g,b,100,convert("作業")]
      i += 1
      csv << [convert(recipe_name),i,convert('T'),convert(recipe_name),r,g,b,100,convert("納車")] 
      csv << [convert(recipe_name),i,convert('F'),convert(recipe_name),r,g,b,100,convert("作業")] 
    end
  end
  
  def part_file_of_order(csv)
    count_sum_index
    i = 0
    i = judge_for_part_file(@sum_uninstall_index,"着工分解",i,csv)
    i = judge_for_part_file(@sum_metal_index,"凹修正鈑金",i,csv)
    i = judge_for_part_file(@sum_cut_index,"カット交換鈑金",i,csv)
    #8.20 start
    i = judge_for_part_file(@sum_frame_amend_set_index,"修正機セット",i,csv)
    #end
    i = judge_for_part_file(@sum_frame_amend_index,"フレーム修正",i,csv)
    i = judge_for_part_file(@sum_metal_putty_index,"鈑金パテ",i,csv)
    i = judge_for_part_file(@sum_putty_index,"塗装パテ",i,csv)
    i = judge_for_part_file(@sum_surface_index,"サフ足付け",i,csv)
    i = judge_for_part_file(@sum_paint_index,"塗装",i,csv)
    i = judge_for_part_file(@sum_assemble_recombine,"組付け組換え",i,csv)
    i = judge_for_part_file(@sum_polish,"磨き",i,csv)
    if self.order_items.count > 0
      csv << [convert(recipe_name),i,convert('F'),TIME_UNIT,convert("納車準備"),convert('F')] 
      i += 1
      csv << [convert(recipe_name),i,convert('F'),TIME_UNIT,convert("納車"),convert('F')] 
    end
  end
  
  
  def recipe_name
    self.placename + self.identity_number + "_" + self.identity_letter + "_" + plate_number
  end
  #对字符串进行编码转换
  def convert(str)
    #require 'iconv'
    begin
      converter = Iconv.new("Shift-JIS", "UTF-8")
      converter.iconv(str)
    rescue
      str
    end
  end
  #塗装指数的时间参数
  def time_index_of_paint
    num = 0
    self.order_items.each do |order_item|
      if order_item.paint_index != 0.0
        num += 1
      end
    end
    index = count_time_index(num)
  end
  #パテ指数的时间参数
  def time_index_of_putty
    num = 0
    self.order_items.each do|order_item|
      if order_item.putty_index != 0.0
        num += 1
      end
    end
  index = count_time_index(num)
  end
 #サフ指数的时间参数
 def time_index_of_surface
   num = 0 
    self.order_items.each do|order_item|
    if order_item.surface_index != 0.0
      num += 1
    end
  end
  index = count_time_index(num)
 end
  
  #单体情况下脱着基本指数的时间参数
  def time_index_of_uninstall
    num = 0
    self.order_items.each do|order_item|
    if order_item.task_type == "単体" && order_item.uninstall_index != 0.0
      num += 1
    end
  end
  index = count_time_index(num)
end

#计算order对象的指数总值
#sum_frame_amend_set_index只有在内板诊断时才会被赋值，而且不论内板损伤部位的个数为多少，该值最大为60分钟，当没有内板部位诊断时该值为0
def count_sum_index
  @sum_uninstall_index = 0.0
  @sum_cut_index = 0.0
  @sum_frame_amend_set_index = 0.0
  @sum_frame_amend_index = 0.0
  @sum_metal_index = 0.0
  @sum_metal_putty_index = 0.0
  @sum_putty_index = 0.0
  @sum_surface_index = 0.0
  @sum_paint_index = 0.0
  @sum_assemble = 0.0
  @sum_recombine = 0.0
  @sum_assemble_recombine = 0.0
  @sum_polish = 0.0
  #如果返回值为真就把该总时间参数设为1,亦即时间为60分钟，不论部位的多少该值最大都只是60分
  if judge_for_sum_frame_amend_set_index 
    @sum_frame_amend_set_index = 1
  end
  self.order_items.each do |order_item|
    @sum_uninstall_index += order_item.uninstall_index 
    @sum_cut_index += order_item.cut_index
    @sum_frame_amend_index += order_item.frame_amend_index
    @sum_metal_index += order_item.metal_index
    @sum_metal_putty_index += order_item.metal_putty_index
    @sum_putty_index += order_item.putty_index
    @sum_surface_index += order_item.surface_index
    @sum_paint_index += order_item.paint_index
    @sum_assemble += order_item.assemble
    @sum_recombine += order_item.recombine
    @sum_assemble_recombine += (order_item.assemble + order_item.recombine)
    @sum_polish += order_item.polish
  end
end
#计算外板order_items个数
  def num_of_out_order_items 
    count = 0
    self.order_items.each do |order_item|
      if order_item.position_id != nil
        count += 1
      end
    end
    return count
  end
  
  def change_order_items_value(use_amend_set)

    self.order_items.each do |order_item|
      if order_item.position_id == nil
        
        if use_amend_set

          order_item.frame_amend_set_index = 1.0
          if order_item.work_judge == "修正から"
            order_item.work_judge = "修正機set_修正から"
            order_item.frame_amend_index = order_item.metal_index
            order_item.metal_index = 0
          elsif order_item.work_judge == "カットから"
            order_item.work_judge = "修正機set_カットから"
            order_item.frame_amend_index = order_item.cut_index
            order_item.cut_index = 0
          end  
          
        else
          order_item.frame_amend_set_index = 0
          
          if order_item.work_judge == "修正機set_修正から"
            order_item.work_judge = "修正から"
            order_item.metal_index = order_item.frame_amend_index
           elsif order_item.work_judge == "修正機set_カットから"
            order_item.work_judge = "カットから"
            order_item.cut_index = order_item.frame_amend_index
          end
          
          order_item.frame_amend_index = 0
        end
        order_item.save
      end
      self.save
    end
  end
  
  def get_direction_side
    direction_side = []
    order_items.each do |order_item|
      if order_item.position
        insert_direction_side(direction_side,order_item)
      end
    end
    return direction_side
  end
  
  def find_positions_in_dir(direction_sides)
    #建立以方向为键，该方向里所有部位的集合为值的hash表
    positions_in_direction_side = {}
    
      direction_sides.each do |direction_side|
        #临时数组，用来存放处于同一方向的部位集
        positions_in_same_dir = []
        order_items.each do |order_item|
          #外板部位才做此操作
          if order_item.position_id
            #当外板部位中order_item.side不为空时side的值就是order_item.side，否则把side设为空字符串
            order_item.side ? side = order_item.side : side = ""
            #筛选条件
            condition = side + order_item.direction
            if condition == direction_side
              positions_in_same_dir << order_item.position.part
            end
          end
        end
      
      positions_in_direction_side["#{direction_side}"] = positions_in_same_dir
      #该数组在进入下一次循环之前设空
      positions_in_same_dir = []
    end
    
    return positions_in_direction_side
  end

#8.19修正
 attr_reader :sum_uninstall_index
 attr_reader :sum_cut_index
 attr_reader :sum_frame_amend_set_index
 attr_reader :sum_frame_amend_index
 attr_reader :sum_metal_index
 attr_reader :sum_metal_putty_index
 attr_reader :sum_putty_index
 attr_reader :sum_surface_index
 attr_reader :sum_paint_index
 attr_reader :sum_assemble
 attr_reader :sum_recombine
 attr_reader :sum_assemble_recombine
 attr_reader :sum_polish
 
private

def insert_direction_side(direction_side,order_item)
    if order_item.side
      dir_item = order_item.side + order_item.direction
    else
      dir_item = order_item.direction
    end
    unless direction_side.find{|item| item == dir_item}
      direction_side << dir_item
    end
  end

#8.20修正
#判断在order对象中的order_items集合中有没有这么一个order_item对象，他的frame_amend_set_index亦即修正机set时间不为0
#如果存在就返回ture，否则返回false
def judge_for_sum_frame_amend_set_index 
  sign = false
  order_items.each do |order_item|
    if order_item.frame_amend_set_index != 0
      sign = true
      return sign
    end
  end  
  return sign
end

#下面3个方法，当该指数总值不为零就加入csv文件作为一行。写入文件中的时间参数是乘以时间削减比例后的总时间。
def judge_for_part_file(sum_index,process_name,i,csv)
  unless sum_index == 0.0
    if process_name == "着工分解"
      csv << [convert(recipe_name),i,convert('F'),(sum_index * TIME_UNIT * time_index_of_uninstall).round,convert(process_name),convert('F')] 
    elsif process_name == "塗装"
      csv << [convert(recipe_name),i,convert('F'),(sum_index * TIME_UNIT * time_index_of_paint).round,convert(process_name),convert('F')] 
    elsif process_name == "サフ足付け"
      csv << [convert(recipe_name),i,convert('F'),(sum_index * TIME_UNIT * time_index_of_surface).round,convert(process_name),convert('F')]
    elsif process_name == "塗装パテ"
      csv << [convert(recipe_name),i,convert('F'),(sum_index * TIME_UNIT * time_index_of_putty).round,convert(process_name),convert('F')]
    else
      csv << [convert(recipe_name),i,convert('F'),(sum_index * TIME_UNIT).round,convert(process_name),convert('F')]
    end
    i += 1
  end
  i
end

def judge_for_partTask_file(sum_index,process_name,i,r,g,b,csv)
  unless sum_index == 0.0
    csv << [convert(recipe_name),i,convert('T'),convert(recipe_name),r,g,b,100,convert(process_name)] 
    csv << [convert(recipe_name),i,convert('F'),convert(recipe_name),r,g,b,100,convert("作業")] 
    i += 1
  end
  i
end

def judge_for_partRelation_file(sum_index,i,csv)
  unless sum_index == 0.0
    csv << [convert(recipe_name),i + 1,convert('S'),i,convert('E'),0] 
    i += 1
  end
  i
end

#根据损伤部位个数计算时间参数
def count_time_index(num)
  index = 0
  case num
    when 0
    index = 0
    when 1
    index = 1
    when 2
    index = 0.65
    when 3
    index = 0.52
  else
    index = 0.42
  end
  index
end


end
